﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using SpaceNeedle.x6473.WindowsPhone.ViewModels;
using Microsoft.Phone.Tasks;
using System.Windows.Media.Imaging;
using System.IO;
using SpaceNeedle.x6473.WindowsPhone.Models;
using Newtonsoft.Json;
using System.Device.Location;
using Microsoft.Phone.Maps.Services;
using System.Text;
using SpaceNeedle.x6473.WindowsPhone.Common;
using Windows.Networking.Connectivity;
using System.Net.Http;
using Microsoft.Devices;
using SpaceNeedle.SDK.WindowsPhone.Views;
using Microsoft.Phone.BackgroundTransfer;
using System.IO.IsolatedStorage;
using SpaceNeedle.SDK.WindowsPhone;
using SpaceNeedle.x6473.WindowsPhone.Common;

namespace SpaceNeedle.x6473.WindowsPhone.Views
{
    public class RequestView : ViewBase<RequestViewModel> { }

    public partial class Request : RequestView
    {
        private bool isPhotoTaken = false;
        private byte[] bytes;
        const int BLOCK_SIZE = 4096;

        private string automaticDectedAddress;
        private string initialCity;

        public Request()
        {
            InitializeComponent();
            this.BackKeyPress += Request_BackKeyPress;
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            if (e.NavigationMode == NavigationMode.New)
            {
                this.ViewModel.LoadCommand.Execute(null);
            }
        }

        void Request_BackKeyPress(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if (this.pictureOptions.Visibility == System.Windows.Visibility.Visible)
            {
                HideCaptureOptions();
                e.Cancel = true;

                return;
            }

            if(MessageBox.Show("Deseja cancelar a criação desta solicitação?", "Solicitação", MessageBoxButton.OKCancel) != MessageBoxResult.OK)
            {
                e.Cancel = true;
            }
            else
            {
                Tracking.SendEvent("Solicitação", "Cancelada", "Envio de Solicitação Cancelado", 0);
            }
        }

        private void OnTakePictureAppBarButton_Click(object sender, EventArgs e)
        {
            HideAppBars();
            this.pictureOptions.Visibility = Visibility.Visible;
        }

        private async void OnSendRequestAppBarButton_Click(object sender, EventArgs e)
        {
            this.addressTextBox.UpdateBinding();
            this.descriptionTextBox.UpdateBinding();

            var locationPositionOnSendRequest = await AppServices.Current.LocationService.GetGeopositionAsync();
            var locationAddressOnSendRequest = await AppServices.Current.LocationService.GetAddressAsync(locationPositionOnSendRequest);

            if (locationAddressOnSendRequest.City != this.ViewModel.CurrentAddress.City)
            {
                MessageBox.Show("Não é possível enviar a sua solicitação pois você não esta na mesma cidade em que o problema se encontra!");
            }
            else
            {

                if (BackgroundTransferService.Requests.Count() >= 25)
                {
                    MessageBox.Show("Você atingiu o número máximo de solicitações na fila! Finalize os envios pendentes ou limpe a lista.");

                    return;
                }

                if (string.IsNullOrEmpty(this.ViewModel.UserTypedAddress) && string.IsNullOrEmpty(this.ViewModel.RequestItem.Address))
                {
                    MessageBox.Show("É necessário informar um endereço para a solicitação. Por favor, preencha o campo corretamente.");

                    this.addressTextBox.Focus();

                    return;
                }

                if (string.IsNullOrEmpty(this.ViewModel.UserTypedDescription))
                {
                    MessageBox.Show("É necessário informar uma descrição para a solicitação. Por favor, preencha o campo corretamente.");

                    this.descriptionTextBox.Focus();

                    return;
                }

                if (!isPhotoTaken)
                {
                    MessageBox.Show("É necessário tirar uma foto para criar a solicitação. Por favor, tire uma nova foto com a câmera do seu celular ou selecione uma foto tirada anteriormente.");
                    this.ShowCaptureOptions();

                    return;
                }

                this.ViewModel.IsInProgress = true;

                bool shareOnSocialNetwork = this.shareCheckBox.IsChecked.Value;

                RequestItem item = this.ViewModel.RequestItem;
                item.Base64Photo = Convert.ToBase64String(bytes);
                item.UserTypedAddress = this.ViewModel.UserTypedAddress;
                item.Description = this.ViewModel.UserTypedDescription;
                //item.Id = id;
                //item.Description = this.descriptionTextBox.Text.Trim();
                //item.Address = automaticDectedAddress.Trim();
                //item.UserTypedAddress = this.addressTextBox.Text.Trim();

                //item.Status = 0;
                //item.Photo = photoUri;

                BackgroundTransferRequest transferRequest = new BackgroundTransferRequest(new Uri(string.Format("http://6473.azurewebsites.net/api/requestitems?shareOnSocialNetwork={0}",
                    shareOnSocialNetwork), UriKind.Absolute));

                transferRequest.TransferPreferences = TransferPreferences.AllowCellularAndBattery;
                transferRequest.Method = "POST";
                transferRequest.Headers.Add("content-type", "application/json");
                transferRequest.Tag = item.Description;

                IsolatedStorageFile isolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();

                if (!isolatedStorage.DirectoryExists("shared/transfers/uploads"))
                {
                    isolatedStorage.CreateDirectory("shared/transfers/uploads");
                }

                using (IsolatedStorageFileStream stream = isolatedStorage.CreateFile("shared/transfers/uploads/" + item.Id + ".json"))
                {
                    byte[] itemBytes = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(item));
                    stream.Write(itemBytes, 0, itemBytes.Length);
                }

                transferRequest.UploadLocation = new Uri("shared/transfers/uploads/" + item.Id + ".json", UriKind.RelativeOrAbsolute);
                BackgroundTransferService.Add(transferRequest);

                if (shareOnSocialNetwork)
                {
                    Tracking.SendSocial(AppViewModel.Instance.Properties.SocialNetworkName, "share", "/solicitacao/" + item.Id);

                }

                Tracking.SendEvent("Solicitação", "Concluída", "Envio de Solicitação Concluído", 0);

                this.ViewModel.IsInProgress = false;

                HideAppBars();
                this.sendRequestMessage.Visibility = Visibility.Visible;

                this.NavigationService.RemoveBackEntry();

                //if(MessageBox.Show("Sua solicitação está sendo enviada. Deseja acompanhar o progresso de envio agora?", "Solicitação", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
                //{
                //    AppServices.Current.NavigationService.NavigateDirect(ViewsUris.Uploads + "?fromRequest=true");

                //    return;
                //}

                //this.NavigationService.GoBack();
            }
        }

        private void ShowCaptureOptions()
        {
            this.HideAppBars();
            this.pictureOptions.Visibility = Visibility.Visible;
        }

        private void OnPhotoBorder_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            this.ShowCaptureOptions();
        }

        private void HideCaptureOptions()
        {
            this.pictureOptions.Visibility = Visibility.Collapsed;
            this.ShowAppBars();
        }

        private void ShowAppBars()
        {
            SystemTray.IsVisible = true;
            this.ApplicationBar.IsVisible = true;
        }

        private void HideAppBars()
        {
            SystemTray.IsVisible = false;
            this.ApplicationBar.IsVisible = false;
        }

        void OnCaptureTask_Completed(object sender, PhotoResult e)
        {
            HideCaptureOptions();

            if (e.TaskResult != TaskResult.OK)
            {
                return;
            }

            using (BinaryReader br = new BinaryReader(e.ChosenPhoto))
            {
                bytes = new byte[e.ChosenPhoto.Length];
                bytes = br.ReadBytes((int)e.ChosenPhoto.Length);
            }

            BitmapImage bmp = new BitmapImage();
            bmp.SetSource(new MemoryStream(bytes));

            this.requestPhotoImage.Source = bmp;

            this.isPhotoTaken = true;
        }

        private void OnCameraButton_Click(object sender, RoutedEventArgs e)
        {
            CameraCaptureTask task = new CameraCaptureTask();
            task.Completed += OnCaptureTask_Completed;
            task.Show();
        }

        private void OnAlbunsButton_Click(object sender, RoutedEventArgs e)
        {
            PhotoChooserTask task = new PhotoChooserTask();
            task.Completed += OnCaptureTask_Completed;
            task.Show();
        }

        private void OnCancelButton_Click(object sender, RoutedEventArgs e)
        {
            HideCaptureOptions();
        }
        

        private void OnTextBox_GotFocus(object sender, RoutedEventArgs e)
        {
            TextBox textBox = (TextBox)sender;
            textBox.SelectAll();
        }

        private void OnMap_ImageOpened(object sender, RoutedEventArgs e)
        {
            this.mapContainer.Visibility = System.Windows.Visibility.Visible;
        }

        private void OnRequestPhotoImage_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            this.ShowCaptureOptions();
        }

        #region Menu Event Handlers
        private void OnUploadsMenuItem_Click(object sender, EventArgs e)
        {
            this.ViewModel.UploadsCommand.Execute(null);
        }

        private void OnAboutMenuItem_Click(object sender, EventArgs e)
        {
            this.ViewModel.AboutCommand.Execute(null);
        }
        

        private void OnSignOutMenuItem_Click(object sender, EventArgs e)
        {
            this.ViewModel.SignOutCommand.Execute(null);
        }

        #endregion

        private void OnOkButton_Click(object sender, RoutedEventArgs e)
        {
            AppServices.Current.NavigationService.NavigateDirect(ViewsUris.Home);
        }

        
    }
}